<?php
namespace app\api\controller\v2;
use app\api\controller\Common;
// use app\common\model\OrderPay;
use app\common\model\Order;

// use app\common\model\OrderDeposit;

define('WXPAY', ROOT_PATH . "wechatpay" . DS);
define('ALIPAY', ROOT_PATH . "alipaywap" . DS);

/**
 *
 *分类管理
 *
 **/
class Pay extends Common {
	protected $noNeedLogin = ['*'];
	protected $noNeedRight = ['*'];
	/**
	 * @var Request Request 实例
	 */
	protected $request;
	/**
	 * 或去分类列表
	 */
	//微信支付回调地址
	public function weixin_pay() {
		require_once ROOT_PATH . 'application/api/PayNotifyCallBack.php';
		$notify = new \PayNotifyCallBack();
		$notify->Handle(false);
	}
	public function get_weixin_prepay_id() {
		$ordersn = $this->postData['ordersn'];
		require_once WXPAY . "lib/WxPay.Api.php";
		require_once WXPAY . "example/WxPay.NativePay.php";
		require_once WXPAY . 'example/log.php';

		$notify = new \NativePay();
		// $payinfo = OrderPay::where('pay_sn', $pay_sn)->find();
		$orderinfo = Order::where('ordersn', $ordersn)->where('status', 0)->find();
		if (empty($orderinfo)) {
			return $this->app_error('订单不存在');
		}
		$return_url = rtrim(APP_URL, "/") . url("v2/pay/weixin_pay");
		$input = new \WxPayUnifiedOrder();
		$input->SetBody($orderinfo['description']);
		$input->SetAttach($orderinfo['description']);
		$input->SetOut_trade_no($orderinfo['ordersn']);
		// $input->SetTotal_fee($orderinfo['totalprice'] * 100);
		$input->SetTotal_fee(1);
		$input->SetGoods_tag($orderinfo['description']);
		$input->SetNotify_url($return_url);
		$input->SetTrade_type("NATIVE");
		$input->SetProduct_id($orderinfo['id']);
		$result = $notify->GetPayUrl($input);
		if ($result['return_code'] == 'FAIL') {
			$this->error($result['return_msg']);
		}
		$return = [
			'prepay_id' => $result['prepay_id'],
			'nonce_str' => $result['nonce_str'],
			'sign' => $result['sign'],
			'timeStamp' => time(),
			'code_url' => $result['code_url'],
		];
		return $this->app_success($return);
	}

	public function get_weixin_jsprepay_id() {
		// 2、根据openid，组装数据，获取prepayid
		require_once WXPAY . "lib/WxPay.Api.php";
		require_once WXPAY . "example/WxPay.NativePay.php";
		require_once WXPAY . 'example/log.php';
		require_once WXPAY . 'lib/WxPay.Data.php';
		require ROOT_PATH . 'wechatpay/lib/WxPay.Config.php';

		$info = 
		// 组装数据
		$newtime = time();
		if ($this->uinfo['openid']) {
			$openid = $this->uinfo['openid'];
		}else{
			$openid = $this->get_wechat_openid($this->postData['code']);
		}

		$input = new \WxPayUnifiedOrder();
		$input->SetBody('购买vip会员');
		$input->SetAttach('购买vip会员');
		$input->SetOut_trade_no($ordersn);
		$input->SetTotal_fee($price);
		$input->SetGoods_tag('购买vip会员');
		$input->SetNotify_url(rtrim(APP_URL, "/") . url("v2/pay/weixin_pay"));
		$input->SetTrade_type("JSAPI");
		$input->SetOpenid($openid);
		$wxPayApi = new \WxPayApi();
		$order = $wxPayApi::unifiedOrder($input);
		// 获取到prepay_id，需要返回给app
		$prepay_id = $order['prepay_id'];
		// 3、生成签名及其他5个字段
		$timeStamp = time();
		$wxconfig = new \WxPayConfig();
		$signArr2 = [
			'appId' => $wxconfig::WX_APPID,
			'nonceStr' => $order['nonce_str'],
			'package' => 'prepay_id=' . $prepay_id,
			'signType' => 'MD5',
			'timeStamp' => $timeStamp,
		];
		$wxdatabase = new \WxPayDataBase();
		$newSign = $wxdatabase->MakeSign2($signArr2);
		$returnData = [
			'timeStamp' => $timeStamp,
			'nonceStr' => $order['nonce_str'],
			'package' => 'prepay_id=' . $prepay_id,
			'signType' => 'MD5',
			'paySign' => $newSign,
		];
		return $returnData;
	}

	protected function get_wechat_openid($code=''){
		require ROOT_PATH . 'wechatpay/lib/WxPay.Config.php';
		// 1、首先根据code获取微信的openid
		$wxconfig = new \WxPayConfig();
		$url = 'https://api.weixin.qq.com/sns/jscode2session';
		$arr = [
			'appid' => $wxconfig::WX_APPID,
			'secret' => $wxconfig::APPSECRET,
			'js_code' => $code,
			'grant_type' => 'authorization_code',
		];
		$data = curlGet($url, $arr);
		$jsonData = json_decode($data, true);
		$openid = $jsonData && isset($jsonData['openid']) ? $jsonData['openid'] : false;
		if ($openid) {
			$this->modelDb->where('userid', $this->uinfo['id'])->setField('openid', $openid);
		}
		return $openid;
	}

	public function alipay_sdkdata() {
		require ALIPAY . 'config.php';
		require ALIPAY . 'aop/AopClient.php';
		require ALIPAY . 'aop/request/AlipayTradeAppPayRequest.php';
		$payinfo = model('Order')->where('pay_sn', $this->request->request('ordersn'))->where('status', 0)->where('createtime', 'egt', (SYS_TIME - config('site.order_time') * 60))->find();
		if (empty($payinfo)) {
			$this->error('订单不存在');
		}
		$aop = new \AopClient();
		$aop->gatewayUrl = $config['gatewayUrl'];
		$aop->appId = $config['app_id'];
		$aop->rsaPrivateKey = $config['merchant_private_key'];
		$aop->format = "json";
		$aop->charset = $config['charset'];
		$aop->signType = $config['sign_type'];
		$aop->alipayrsaPublicKey = $config['alipay_public_key'];
		//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
		$request = new \AlipayTradeAppPayRequest();
		//SDK已经封装掉了公共参数，这里只需要传入业务参数
		$body = [
			'subject' => $payinfo['descrip'],
			'out_trade_no' => $payinfo['pay_sn'],
			'timeout_express' => config('site.order_time') . 'm',
			'total_amount' => $payinfo['pay_price'],
			'product_code' => 'QUICK_MSECURITY_PAY',
		];
		$bizcontent = json_encode($body);
		$request->setNotifyUrl($config['notify_url']);
		$request->setBizContent($bizcontent);
		//这里和普通的接口调用不同，使用的是sdkExecute
		$return = $aop->sdkExecute($request);
		$this->success('', ['paystr' => $return]);
	}

	//支付宝回调

	public function alipay_return() {

		require_once ALIPAY . "config.php";

		require_once ALIPAY . "aop/AopClient.php";

		$postdata = $this->request->request();

		// trace($postdata);

		unset($postdata['s']);

		//计算得出通知验证结果
		$aop = new \AopClient();

		$aop->alipayrsaPublicKey = $config['alipay_public_key'];

		$verify_result = $aop->rsaCheckV1($postdata, '', $config['sign_type']);

		// trace($verify_result);

		if ($verify_result) {
//验证成功

			$out_trade_no = $postdata['out_trade_no'];

			//支付宝交易号

			$trade_no = $postdata['trade_no'];

			//交易状态

			if ($postdata['trade_status'] == 'TRADE_FINISHED') {

				model("OrderPay")->pay_fail_unlock($out_trade_no);

				exit('fail');

			} elseif ($postdata['trade_status'] == 'TRADE_SUCCESS') {

				// trace($postdata['buyer_pay_amount']);

				$err = model("OrderPay")->pay_success($out_trade_no, $trade_no, 1, $postdata['buyer_pay_amount']);

				if (!$err) {

					exit('fail');

				}

			}

			exit("success"); //请不要修改或删除

		} else {

			exit("fail");

		}

	}

}